package com.user.seat.filter;

import com.user.seat.utils.JwtService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jimmy
 * Date  2022/4/21 16:42
 * @version 1.0
 */
//@WebFilter(filterName="FirstFilter",urlPatterns="/*")
public class LoginFilter  implements Filter {

    @Autowired
    private JwtService jwtService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Map<String, String> map = new HashMap<>();
        String url = ((HttpServletRequest) servletRequest).getRequestURI();
        if (url != null) {
            //登录请求直接放行

//            if (url.contains("login") || "/".contains(url) || url.contains("register")) {
//                filterChain.doFilter(servletRequest, servletResponse);
//                return;
//            } else {
//                //其他请求验证token
//                String token = ((HttpServletRequest) servletRequest).getHeader("token");
//                if (StringUtils.isNotBlank(token)) {
//                    //token验证结果
//                    int verify = jwtService.verify(token);
//                    if (verify != 1) {
//                        //验证失败
//                        if (verify == 2) {
//                            map.put("errorMsg", "token已过期");
//                        } else if (verify == 0) {
//                            map.put("errorMsg", "用户信息验证失败");
//                        }
//                    } else if (verify == 1) {
//                        //验证成功，放行
//                        filterChain.doFilter(servletRequest, servletResponse);
//                        return;
//                    }
//                } else {
//                    //token为空的返回
//                    map.put("errorMsg", "未携带token信息");
//                }
//            }
            filterChain.doFilter(servletRequest, servletResponse);
            return;
//            JSONObject jsonObject = JSONObject.fromObject(map);
//            servletResponse.setContentType("application/json");
//            //设置响应的编码
//            servletResponse.setCharacterEncoding("utf-8");
//            //响应
//            PrintWriter pw = servletResponse.getWriter();
//            pw.write(jsonObject.toString());
//            pw.flush();
//            pw.close();
        }
    }
}
